package sun.misc;


import java.lang.reflect.Field;

/**
 * @author Khai Loon
 * @since 2018/5/23
 */
public class UnsafeTest {

    private int age = 18;

    private int[] intArr = new int[]{7, 8, 9};

    static {
        try {
            UnsafeTest test = new UnsafeTest();
            Field field = Unsafe.class.getDeclaredField("theUnsafe");
            field.setAccessible(true);
            Unsafe unsafe = (Unsafe) field.get(null);


            //直接获取对象
            UnsafeTest create = (UnsafeTest) unsafe.allocateInstance(UnsafeTest.class);

            //age 对象偏移量
            long ageffset = unsafe.objectFieldOffset(UnsafeTest.class.getDeclaredField("age"));
            System.out.println("age 偏移地址" + ageffset);
            System.out.println("age 值===" + unsafe.getIntVolatile(test, ageffset));

            //数组 第一个元素的地址
            long baseOffset = unsafe.arrayBaseOffset(int[].class);
            System.out.println("str 基础偏移地址" + baseOffset);

            //数组中每个元素占用的大小 复杂元素同理 java.util.concurrent.ConcurrentHashMap.Node 一样的
            long scale = unsafe.arrayIndexScale(int[].class);
            unsafe.putInt(test.intArr, baseOffset + scale, 11);
            unsafe.putInt(test.intArr, baseOffset + scale*2, 22);
            System.out.println("intArr[0] 值===" + unsafe.getIntVolatile(test.intArr, baseOffset + scale));
            System.out.println("intArr[1] 值===" + unsafe.getIntVolatile(test.intArr, baseOffset + scale*2));

            //CAS
            unsafe.compareAndSwapInt(test.intArr, baseOffset + scale, 11, 22);
            System.out.println("str cas 修改 值===" + unsafe.getIntVolatile(test.intArr, baseOffset + scale));

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        new UnsafeTest();
    }
}



